package uk.org.tiro.android.spacepostcard;

/* More or less directly taken from PictureDemo app from Busy Coders Guide
   to Android:http://commonsware.com/Android/
*/

import android.app.Activity;

import android.util.Log;

import android.os.Bundle;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Environment;

import android.hardware.Camera;
import android.graphics.PixelFormat;

import android.view.SurfaceHolder;
import android.view.SurfaceView;

import android.widget.Toast;
import android.widget.TextView;

import java.io.File;
import java.io.FileOutputStream;

public class SpacePostcard extends Activity
{
    private SurfaceView preview = null;
    private SurfaceHolder previewHolder = null;
    private Camera camera = null;
    private boolean inPreview=false;
    private Handler mHandler = new Handler();
    private int picture_count = 0;

//    Camera.Parameters parameters = camera.get
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

	// Setup camera
	preview = (SurfaceView)findViewById(R.id.space_preview);
	previewHolder = preview.getHolder();
	previewHolder.addCallback(surfaceCallback);
	previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

	// TODO - read camera settings ?

	// Setup sensors connection (USB?)

	// Run for period / until stopped

		// takePicture()

		// readSensors()


	// End - Transmit saved data ?
    }

    private Runnable takePicture = new Runnable() {
    	public void run() {

//		TextView countView;

    		if(picture_count >= 10) {

			mHandler.removeCallbacks(takePicture);

		} else {

			mHandler.postDelayed(takePicture, 10000);
		}
		
		picture_count++;

//		countView = (TextView)findViewById(R.id.picture_num);

//		countView.setText(Integer.toString(picture_count));

    		camera.takePicture(null, null, spacephotoCallback);


	}
    };

    @Override
    public void onResume() {
	super.onResume();

	camera = Camera.open();
	camera.setDisplayOrientation(90);
    }
 

    private Camera.Size getBestPreviewSize(int width, int height,
										
										
 Camera.Parameters parameters) {
		Camera.Size result=null;
		
		for (Camera.Size size : parameters.getSupportedPreviewSizes()) {
			if (size.width<=width && size.height<=height) {
				if (result==null) {
					result=size;
				}
				else {
					int resultDelta=width-result.width+height-result.height;
					int newDelta=width-size.width+height-size.height;
					
					if (newDelta<resultDelta) {
						result=size;
					}
				}
			}
		}
		
		return(result);
    }

    SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {
    	public void surfaceCreated(SurfaceHolder holder) {
		try {
			camera.setPreviewDisplay(previewHolder);

			// Every 10 seconds
			mHandler.postDelayed(takePicture, 10000);
		}
		catch(Throwable t) {
			Log.e("SpacePostcard-surfacecallback",
				"Exception in setPreviewDisplay()", t);
			Toast.makeText(SpacePostcard.this, t.getMessage(), Toast.LENGTH_LONG).show();
		}
	}

	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
			Camera.Parameters parameters =camera.getParameters();
			Camera.Size size=getBestPreviewSize(width, height, parameters);

			if(size!=null) {
				parameters.setPreviewSize(size.width, size.height);
				parameters.setPictureFormat(PixelFormat.JPEG);
				camera.setParameters(parameters);
				camera.startPreview();
				inPreview=true;
			}
	    }

	 public void surfaceDestroyed(SurfaceHolder holder) {
	 	// TODO anything ?
		camera.stopPreview();
		camera.release();
		camera=null;
	}
   };


    Camera.PictureCallback spacephotoCallback = new Camera.PictureCallback() {
    	public void onPictureTaken(byte[] data, Camera Camera) {
		new SaveSpacePhotoTask().execute(data);
		camera.startPreview();
	}
    };

    class SaveSpacePhotoTask extends AsyncTask<byte[], String, String> {
    	
	@Override
	protected String doInBackground(byte[]... jpeg) {
		// TODO get current timestamp
		String timestamp = Integer.toString(picture_count);

		File photo = new File(Environment.getExternalStorageDirectory(),
				"spacepostcard-" + timestamp + ".jpg");

		try {
			FileOutputStream fos = new FileOutputStream(photo.getPath());
			fos.write(jpeg[0]);
			fos.close();
		}
		catch (java.io.IOException e) {
			Log.e("SpacePostcard", "Exception in photoCallback", e);
		}

		return(null);
	}
     }
}
